<?php
/**
 * Created by PhpStorm.
 * User: wangsentao
 * Date: 2018/3/2
 * Time: 下午3:36
 */

namespace app\api\repository;


use app\common\Model\Order;
use app\common\Service;
use think\Db;

class OrderRespository extends Service
{
    /**
     * 生成充值订单
     * @param $order_type 订单类型
     * @param $app_type  订单来源
     * @param $pay_type  支付方式
     */
    public function createOrder($uid, $order_type, $app_type, $pay_type)
    {
        $model = model("app\common\Model\Order");
        $model->uid = $uid;
        $model->type = $order_type;
        $model->status = Order::$order_status['WAIT_PAY_ORDER'];
        $model->order_num = self::createOrderNum($order_type);
        $model->app_type = $app_type;
        $model->pay_type = $pay_type;

        if ($model->save()) {
            return $model->getData();
        }

        return $model->getError();
    }

    /**
     * 更新支付订单 记录状态
     */
    public function updateOrderPayedStatus($order_num = null, $order_id = null, $trade_no = '')
    {
        if ($order_num == null && $order_id == null) {
            return [
                'code' => '100031',
                'msg' => '订单号或订单ID只允许一个为空',
            ];
        }

        $model = model("app\common\Model\Order");

        if ($order_num == null) {
            $model->where('id', $order_id);
        }

        if ($order_id == null) {
            $model->where('order_num', $order_num);
        }

        $model->status = Order::$order_status['YET_PAY_ORDER'];

        $res = $model->isUpdate(true)->save();
        return [
            'code' => '000000',
            'data' => $res,
        ];
    }

    /**
     * 生成唯一订单号
     * @param $order_type
     * @return string
     */
    public static function createOrderNum($order_type)
    {
        return Order::$orders[$order_type] . date("YmdHis") . dechex(date('m'));
    }

    /**
     * 未区分业务表逻辑
     * 根据订单号获取订单的详情
     * @param $order_num
     */
    public function getOrderInfoByOrderId($order_id)
    {
        if (empty($order_id)) {
            return [
                'code' => '10002',
                'msg' => '订单号不能为空',
            ];
        }
        return Db::table('sh_order_info_shaohuo')
            ->alias('sh')
            ->join('order', 'sh.order_id=order.id')
            ->where('sh.order_id', $order_id)
            ->field('order.id as order_id,order.status as or_status,sh.uid,sh.order_num,sh.fc_id,sh.status as sh_status,sh.shipping_fee,sh.func_name')
            ->find();
    }

}